import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
import { ChatMessageHistory } from "langchain/memory";
import { HumanMessage, AIMessage } from "@langchain/core/messages";
import {
  ChatPromptTemplate,
  MessagesPlaceholder,
} from "@langchain/core/prompts";

// const history = new ChatMessageHistory();
// await history.addMessage(new HumanMessage("hi"));
// await history.addMessage(new AIMessage("What can I do for you?"));

// const messages = await history.getMessages();

// console.log(messages);
const chatModel = new ChatOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  configuration: {
    baseURL: process.env.OPENAI_API_BASE,
  },
});
const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    `You are a helpful assistant. Answer all questions to the best of your ability.
    You are talkative and provides lots of specific details from its context. 
    If the you does not know the answer to a question, it truthfully says you do not know.`,
  ],
  new MessagesPlaceholder("history_message"),
]);

const chain = prompt.pipe(chatModel);

const history = new ChatMessageHistory();
await history.addMessage(new HumanMessage("hi, my name is Kai"));

const res1 = await chain.invoke({
  history_message: await history.getMessages(),
});

console.log(res1);

await history.addMessage(res1);
await history.addMessage(new HumanMessage("What is my name?"));

const res2 = await chain.invoke({
  history_message: await history.getMessages(),
});

console.log(res2);
